package com.gxuwz.stats.service.impl;

import com.gxuwz.stats.service.FileParser;
import com.gxuwz.stats.service.FileParserType;
import com.gxuwz.stats.service.SheetHandler;
import com.gxuwz.stats.service.SheetName;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@FileParserType("pdf")
public class ExcelParser implements FileParser {
    private final Map<String, SheetHandler> sheetHandlers = new HashMap<>();

    @Autowired
    public ExcelParser(List<SheetHandler> handlers) {
        for (SheetHandler handler : handlers) {
            // 获取处理器类上的 @SheetName 注解
            SheetName annotation = handler.getClass().getAnnotation(SheetName.class);
            if (annotation != null) {
                sheetHandlers.put(annotation.value(), handler);
            } else {
                throw new IllegalStateException("SheetHandler 缺少 @SheetName 注解: " + handler.getClass());
            }
        }
    }


    @Override
    public void parse(MultipartFile file) throws IOException {
        try (Workbook workbook = new XSSFWorkbook(file.getInputStream())) {
            for (Sheet sheet : workbook) {
                String sheetName = sheet.getSheetName();
                SheetHandler handler = sheetHandlers.get(sheetName);
                if (handler != null) {
                    handler.handle(sheet);
                }
            }
        }
    }
}
